<script setup>
import { ref, reactive, nextTick } from 'vue'
import { ElMessage, ElLoading, ElMessageBox } from 'element-plus'
import LayoutRightContainer from '@/views/layout-right-container.vue'
import EditorComponent from '@/components/EditorComponent.vue'
import {
    fetchServiceClassifyList, fetchServiceBasic, fetchServiceCreate,
    fetchServiceRemove, fetchServiceChangeStatus
} from '@/api/service.services.js'
import {
    Plus, Delete, Edit, SuccessFilled,
    CircleCloseFilled, TurnOff
} from '@element-plus/icons-vue'
const breadcrumb = ref([
    { label: '服务中心' },
    { label: '服务项目管理' }
])
const searchForm = ref({
    total: 0,
    page: 1,
    limit: 20
})
const show = ref(false)
const addForm = ref({})
const formRules = reactive({
    name: [{ required: true, message: '请输入服务项目名称', trigger: 'blur' }],
    description: [{ required: true, message: '请输入服务项目描述', trigger: 'blur' }],
    classify_id: [{ required: true, message: '请选择服务分类', trigger: 'change' }],
    thumbnail: [{ required: true, message: '请上传缩略图', trigger: 'change' }],
    main_image: [{ required: true, message: '请上传主图', trigger: 'change' }],
    disable: [{ required: true, message: '请选择启用状态', trigger: 'change' }],
    is_top: [{ required: true, message: '请选择首页推荐', trigger: 'blur' }]
})

// 添加tableData和loading的定义
const tableData = ref([])
const loading = ref(false)
const editorRef = ref(null)
const submit = async () => {
    addForm.value.content = editorRef.value.valueHtml
    // 检查addFormRef是否存在
    if (!addFormRef.value) {
        ElMessage.error('表单初始化失败，请重试')
        return
    }
    const valid = await addFormRef.value.validate()
    if (!valid) return
    const addLoading = ElLoading.service({
        lock: true,
        text: 'Loading',
        background: 'rgba(0, 0, 0, 0.7)',
    })

    const result = await fetchServiceCreate(addForm.value)
    if (result.code == 1) {
        show.value = false
        addLoading.close()
        ElMessage.success(addForm.id ? '编辑成功' : '添加成功')
        initTableData()
    }
}

const addFormRef = ref(null)
const beforeUpload = (file) => {
    // 使用FileReader将图片转换为base64格式
    const reader = new FileReader()
    reader.onload = (e) => {
        addForm.value.main_image = reader.result // 将base64数据存储到表单中
    }
    reader.readAsDataURL(file.raw)
}
const beforeThumbnailUpload = (file) => {
    // 使用FileReader将图片转换为base64格式
    const reader = new FileReader()
    reader.onload = (e) => {
        addForm.value.thumbnail = reader.result // 将base64数据存储到表单中
    }
    reader.readAsDataURL(file.raw)
}
const classify = ref([])
const initServiceClassify = async () => {
    const result = await fetchServiceClassifyList()
    if (result.code === 1) {
        classify.value = result.data
    }
}

const initTableData = async () => {
    loading.value = true
    const result = await fetchServiceBasic(searchForm.value)
    if (result.code == 1) {
        loading.value = false
        searchForm.value.total = result.data.total
        tableData.value = result.data.data
    }
}
initTableData()
initServiceClassify()
const handleCurrentChange = (page) => {
    searchForm.value.page = page
    initTableData()
}

const handleSizeChange = (limit) => {
    searchForm.value.limit = limit
    searchForm.value.page = 1
    initTableData()
}
const remove = async (ids) => {
    try {
        await ElMessageBox.confirm('确定删除所选服务项目吗？')
        const result = await fetchServiceRemove({ id: ids })
        if (result.code == 1) {
            initTableData()
            ElMessage.success('删除成功')
        }

    } catch (error) {
        console.log(error)
    }
}
const handleUpload = (file) => {
    console.log('handleUpload', file)
}
const editOpen = (row) => {
    show.value = true
    addForm.value = row
    nextTick(() => {
        editorRef.value.valueHtml = row.content
    })
}

const disable = async (params) => {
    const result = await fetchServiceChangeStatus(params)
    if (result.code == 1) {
        ElMessage.success('操作成功')
    }
}
</script>
<template>
    <LayoutRightContainer :breadcrumb="breadcrumb">
        <div :class="$style['main-container']">
            <div :class="$style['search-container']">
                <el-form :model="searchForm" :class="$style['form-warpper']" inline>
                    <el-form-item>
                        <el-input v-model="searchForm.name" placeholder="请输入服务项目名称" clearable />
                    </el-form-item>
                    <el-form-item>
                        <el-select v-model="searchForm.classify_id" placeholder="服务分类" clearable>
                            <el-option v-for="(item, index) in classify" :key="index" :label="item.name"
                                :value="item.id" />
                        </el-select>
                    </el-form-item>
                    <el-form-item>
                        <el-button type="primary" @click="initTableData">查询</el-button>
                    </el-form-item>
                </el-form>
                <el-button type="primary" :icon="Plus" @click="addForm = {}; show = true">添加</el-button>
            </div>
            <el-table :data="tableData" ref="refTable" row-key="id" :class="$style['table-wrapper']"
                v-loading="loading">
                <el-table-column label="服务项目名称" prop="name" align="center" />
                <el-table-column label="缩略图" align="center">
                    <template #default="{ row }">
                        <el-image v-if="row.thumbnail" :src="row.thumbnail" :class="$style['images-wrapper']"
                            :preview-src-list="[row.thumbnail]" fit="cover" preview-teleported />
                    </template>
                </el-table-column>
                <el-table-column label="主图" align="center">
                    <template #default="{ row }">
                        <el-image v-if="row.main_image" :src="row.main_image" style="width: 100px;height:50px;"
                            :preview-src-list="[row.main_image]" fit="cover" preview-teleported />
                    </template>
                </el-table-column>
                <el-table-column label="服务分类" prop="classify_name" align="center" />
                <el-table-column label="价格" align="center">
                    <template #default="{ row }">
                        {{ row.price ? row.price : '面议' }}
                    </template>
                </el-table-column>
                <el-table-column label="启用状态" prop="disable" align="center">
                    <template #default="{ row }">
                        <el-icon v-if="row.disable == 1" color="#40bf40">
                            <SuccessFilled />
                        </el-icon>
                        <el-icon v-else color="#cccccc">
                            <CircleCloseFilled />
                        </el-icon>
                    </template>
                </el-table-column>
                <el-table-column label="首页推荐" align="center">
                    <template #default="{ row }">
                        <el-icon v-if="row.is_top == 1" color="#40bf40">
                            <SuccessFilled />
                        </el-icon>
                        <el-icon v-else color="#cccccc">
                            <CircleCloseFilled />
                        </el-icon>
                    </template>
                </el-table-column>
                <el-table-column label="操作" align="center" width="310px">
                    <template #default="{ row }">
                        <div :class="$style['tools-wrapper']">
                            <el-link type="primary" :icon="Edit" @click="editOpen(row)" :underline="false">编辑</el-link>
                            <el-link type="danger" :icon="Delete" :underline="false"
                                @click="remove([row.id])">删除</el-link>
                            <el-link v-if="row.disable == 2" type="success" :icon="Open" :underline="false"
                                @click="disable({ id: row.id, disable: 1 })">启用</el-link>
                            <el-link v-if="row.disable == 1" :icon="TurnOff" :underline="false"
                                @click="disable({ id: row.id, disable: 2 })">禁用</el-link>
                            <el-link v-if="row.is_top == 2" type="success" :icon="Open" :underline="false"
                                @click="disable({ id: row.id, is_top: 1 })">首页推荐</el-link>
                            <el-link v-if="row.disable == 1" :icon="TurnOff" :underline="false"
                                @click="disable({ id: row.id, is_top: 2 })">取消首页推荐</el-link>
                        </div>
                    </template>
                </el-table-column>
            </el-table>
            <div :class="$style['flex-end']">
                <el-pagination v-model:current-page="searchForm.page" v-model:page-size="searchForm.limit" size="small"
                    background layout="sizes,total,prev, pager, next" :total="searchForm.total"
                    :hide-on-single-page="false" :page-sizes="[20, 50, 100, 200]" @size-change="handleSizeChange"
                    @current-change="handleCurrentChange" />
            </div>
        </div>
    </LayoutRightContainer>

    <el-drawer v-model="show" :title="addForm.id ? '编辑' : '添加'" :size="1200" :close-on-click-modal="false"
        :close-on-press-escape="false" :class="$style['drawer-container']">
        <el-form ref="addFormRef" :model="addForm" :rules="formRules" label-width="100px"
            :class="$style['form-container']">
            <el-form-item label="服务项目" prop="name">
                <el-input v-model="addForm.name" placeholder="请输入服务项目名称" />
            </el-form-item>
            <el-form-item label="服务分类" prop="classify_id">
                <el-select v-model="addForm.classify_id" placeholder="请选择服务分类" clearable>
                    <el-option v-for="(item, index) in classify" :key="index" :label="item.name" :value="item.id" />
                </el-select>
            </el-form-item>
            <el-form-item label="服务价格">
                <el-input-number v-model="addForm.price" :precision="2" :step="0.1" placeholder="请输入服务项目价格" />
            </el-form-item>
            <el-form-item label="服务简介" prop="description">
                <el-input type="textarea" :rows="2" v-model="addForm.description" placeholder="请输入服务简介" />
            </el-form-item>
            <el-form-item label="启用状态" prop="disable">
                <el-radio-group v-model="addForm.disable">
                    <el-radio :value="1">启用</el-radio>
                    <el-radio :value="2">禁用</el-radio>
                </el-radio-group>
            </el-form-item>
            <el-form-item label="首页推荐" prop="is_top">
                <el-radio-group v-model="addForm.is_top">
                    <el-radio :value="1">首页推荐</el-radio>
                    <el-radio :value="2">取消首页推荐</el-radio>
                </el-radio-group>
            </el-form-item>
            <el-form-item label="缩略图" prop="thumbnail">
                <el-upload :class="$style['thumbnail-uploader']" :show-file-list="false"
                    :on-change="beforeThumbnailUpload" :http-request="handleUpload">
                    <img :src="addForm.thumbnail" :class="$style['thumbnail']"
                        v-if="addForm.thumbnail && typeof addForm.thumbnail === 'string'" />
                    <el-icon :class="$style['thumbnail-uploader-icon']" v-else>
                        <Plus />
                    </el-icon>
                </el-upload>
            </el-form-item>
            <el-form-item label="主图" prop="main_image">
                <el-upload :class="$style['image-uploader']" :show-file-list="false" :on-change="beforeUpload"
                    :http-request="handleUpload">
                    <img :src="addForm.main_image" :class="$style['avatar']"
                        v-if="addForm.main_image && typeof addForm.main_image === 'string'" />
                    <el-icon :class="$style['avatar-uploader-icon']" v-else>
                        <Plus />
                    </el-icon>
                </el-upload>
            </el-form-item>
            <el-form-item label="服务内容" prop="content">
                <div :class="$style['editor-container']">
                    <EditorComponent ref="editorRef" />
                </div>
            </el-form-item>
        </el-form>
        <template #footer>
            <div style="flex: auto">
                <el-button @click="addForm = {}; show = false">取消</el-button>
                <el-button type="primary" @click="submit">提交</el-button>
            </div>
        </template>
    </el-drawer>
</template>
<style lang="scss" module>
.main-container {
    display: flex;
    flex-direction: column;
    height: 100%;
    background: #FFF;
    border-radius: 5px;
    box-shadow: 0 1px 4px rgba(0, 0, 0, 0.06);
    padding: 0 10px;
}

.search-container {
    display: flex;
    flex-direction: row;
    height: 50px;
    align-items: center;
    justify-content: space-between;
}

.form-warpper {

    & [class~='el-form-item'] {
        margin-bottom: 0;
        margin-right: 10px;
    }

    & [class~='el-input'] {
        width: 200px;
    }

    & [class~='el-select'] {
        width: 200px;
    }
}

.table-wrapper {
    flex: 1;

    & [class~='el-table__cell'] {
        z-index: initial;
    }
}

.flex-end {
    display: flex;
    justify-content: flex-end;
    align-items: center;
    height: 35px;
}

.tools-wrapper {
    display: flex;
    flex-direction: row;
    justify-content: center;

    & [class~='el-link'] {
        margin-right: 15px;
    }
}

.thumbnail-uploader {
    width: 120px;
    height: 120px;
}

.thumbnail {
    width: 120px;
    height: 120px;
    display: block;
    border: 1px dashed var(--el-border-color);
}

.thumbnail-uploader-icon {
    font-size: 28px;
    color: #ccc;
    width: 120px;
    height: 120px;
    text-align: center;
    border: 1px dashed var(--el-border-color);
}


.image-uploader {
    width: 280px;
    height: 120px;
}

.avatar {
    width: 280px;
    height: 120px;
    display: block;
    border: 1px dashed var(--el-border-color);
}

.avatar-uploader-icon {
    font-size: 28px;
    color: #ccc;
    width: 280px;
    height: 120px;
    text-align: center;
    border: 1px dashed var(--el-border-color);
}

.form-container {
    & [class~='el-input-number'] {
        width: 80%;
    }

    & [class~='el-input'] {
        width: 80%;
    }

    & [class~='el-select'] {
        width: 80%;
    }

    & [class~='el-textarea'] {
        width: 80%;
    }
}

.images-wrapper {
    width: 50px;
    height: 50px;
}
</style>
